package com.dean.utils;

import com.dean.exception.DeanRuntimeException;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * dean csv 工具类
 */
public class DeanApacheCsvUtils {
    private static  final Logger logger = LoggerFactory.getLogger(DeanApacheCsvUtils.class);
    // 表头bom
    private static final String BOM="\uFEFF";

    public static void main(String[] args) {
        DeanApacheCsvUtils deanApacheCsvUtils = new DeanApacheCsvUtils();
        deanApacheCsvUtils.readCsv("d:/dean/test/test.csv",new String[]{"COL1"},",");
    }



    public List<List<String>> readCsv(String fileName,String [] head,String delimiter) {
        List<List<String>> data = new ArrayList<List<String>>();
        CSVFormat csvFormat = CSVFormat.RFC4180.builder().setTrim(false).setHeader(head).setSkipHeaderRecord(false).setDelimiter(delimiter).build();
        try(CSVParser parser = csvFormat.parse(new InputStreamReader(new FileInputStream(fileName),"Utf-8"))){
            parser.stream().forEach(
                row->{
                    logger.debug("row:{}",row);
                    data.add(row.toList());
                }
            );
        } catch (IOException exception) {
            logger.error("读取csv文件出错:",exception.getMessage(),exception);
            throw DeanRuntimeException.throwException(996, exception.getMessage());
        }

        return data;
    }

    /**
     * csv 文件写入
     * @param fileName
     * @param delimiter
     * @param head
     * @param data
     */
    public void writeCsv(String fileName, String delimiter, String [] head, String[][] data){
        CSVFormat csvFormat = CSVFormat.RFC4180.builder().setDelimiter(delimiter).setTrailingDelimiter(false).setHeader(head).build();
        try(CSVPrinter printer = csvFormat.print(Paths.get(fileName), Charset.forName("UTF-8"))) {
            printer.printRecords(data);
            printer.flush();
        } catch (IOException e) {
            logger.error("生成csv文件失败,失败原因:{}",e.getMessage(),e);
            throw DeanRuntimeException.throwException(996,e.getMessage());
        }
    }

    public static void writeCsv(String fileName, String delimiter, List<List<String>> datas){
        CSVFormat csvFormat = CSVFormat.RFC4180.builder().setDelimiter(delimiter).setTrailingDelimiter(false).build();
        try(CSVPrinter printer = csvFormat.print(Paths.get(fileName), Charset.forName("UTF-8"))) {
            printer.printRecords(datas);
            printer.flush();
        } catch (IOException e) {
            logger.error("生成csv文件失败,失败原因:{}",e.getMessage(),e);
            throw DeanRuntimeException.throwException(996,e.getMessage());
        }
    }
}
